import React from 'react';
import {StyleSheet, FlatList} from 'react-native';
import {
  Button,
  TouchableOpacity,
  Text,
  View,
  TextField
} from 'react-native-ui-lib';
import {isIPhoneX} from '../../configs/platform';
import {commonStyles} from '../../configs/commonStyle';
import ListSeparator from '../common/ListSeparator';
import moment from 'moment';
import navigator from '../../utils/navigator'; 
import BasePage from '../BasePage';
import NavigationBar from '../common/NavigationBar';
import ViewUtils from '../../utils/ViewUtils';
import Events from '../../utils/events';
import ConfirmDialog from "../common/ConfirmDialog";
import { saveWorkOrderModify } from '../../net/order';
import ToastUtils from '../../utils/ToastUtils';
import PickerTypeDialog from '../common/PickerTypeDialog';
import {Icon} from '../components';

const reasonList = ['卡点已沟通延迟','真实号码收不到短信','真实号码回复失败','联系不上已沟通延迟','虚拟号修改时间','客户修改地址','定位错误']

export default class ModifyOrder extends BasePage {
  constructor(props) {
    super(props);
    const params = this.props.navigation.state.params
    logger(JSON.stringify(params.order))
    this.state = {
      isOpen: false,
      data: params.order || {},
      dataList: [],
      reasonIndex: 0,
      reason: '',
      address: {
        name: '',
        longitude: '',
        latitude: '',
      },
      timer: {
        delySTime: '',
        delyETime: '',
      },
    };
  }

  componentDidMount() {
    this.init(this.state.data);
    this.getAddress = Events.subscribe("ModifyOrder-getAddress", (addressData) => {
      this.setState({
        address: {
          name: addressData.name,
          longitude: addressData.longitude,
          latitude: addressData.latitude,
        },
      })
    });
  }

  componentWillUnmount() {
    this.getAddress && this.getAddress.remove();
  }

  init = (data) => {
    let start = moment().format('HH');

    let dataList = [];
    for (let i = Number(start) + 1; i < 24; i++) {
      dataList.push({
        startTime: i + ':00',
        endTime: i == 23 ? i + ':59' : i + 1 + ':00',
        isChecked: false,
      });
    }
    this.setState({
      isOpen: true,
      data,
      dataList,
      timer: {delySTime: '', delyETime: ''},
      address: {
        name: '',
        longitude: '',
        latitude: '',
      }
    });
  }

  validateParams = () => {
    const {address, timer, reason} = this.state
    if (!address.name && !timer.delySTime) {
      ToastUtils.showInfo('无修改内容');
      return false;
    }
    if (!reason) {
      ToastUtils.showInfo('请选择修改原因');
      return false;
    }
    return true;
  }

  submit = () => {
    const {data, reason, address, timer} = this.state;
    const extJson = {};
    if (address.name) {
      extJson['receiverAddress'] = address.name;
      extJson['longitude'] = address.longitude;
      extJson['latitude'] = address.latitude;
    }
    if (timer.delySTime) {
      const year = new Date().getFullYear();
      extJson['deliveryStartTime'] = `${year}-${data.delyTime} ${timer?.delySTime}:00`;
      extJson['deliveryEndTime'] = `${year}-${data.delyTime} ${timer?.delyETime}:${timer?.delyETime.includes('59') ? '59' : '00'}`;
    }
    const params = {
      orderId: data.ordNo,
      platformOrderId: data.platformOrderId,
      xmbzNo: data.xmbzNo,
      cityId: data.cityId,
      cityName: data.cityName,
      reason: reason,
      extJson: JSON.stringify(extJson)
    }
    saveWorkOrderModify(params).then(res => {
      ToastUtils.showSuccessInfo('提交成功');
      this._onBackPress();
    }).catch(res => {
      ToastUtils.showFailInfo(res.msg || '提交失败');
    })
  }

  render_item = ({item, index}) => {
    const {dataList, address} = this.state;
    return (
      <TouchableOpacity
        activeOpacity={1}
        style={item?.isChecked ? styles.itemWrap_checked : styles.itemWrap}
        onPress={() => {
          if (item?.isChecked == false) {
            const timer = {};
            const tempList = dataList.map((timeItem, pos) => {
              timeItem['isChecked'] = index == pos;
              if (timeItem['isChecked']) {
                timer.delySTime = timeItem.startTime;
                timer.delyETime = timeItem.endTime;
              }
              return timeItem;
            });
            this.setState({dataList: tempList, timer: timer});
          }
        }}>
        <Text style={commonStyles.text_black}>
          {`${item?.startTime} - `}
          {`${item?.endTime}`}
        </Text>
      </TouchableOpacity>
    );
  };

  render() {
    const {data, dataList, timer, address, reason, reasonIndex} = this.state;
    return (
      <View useSafeArea style={commonStyles.body_primary}>
        <NavigationBar
          title={'修改订单信息'}
          backgroundColor={'transparent'}
          leftButton={ViewUtils.getLeftButton(() => this._onBackPress())}
        />
        <View style={{...commonStyles.container, padding: 20}}>
          <Text style={{...commonStyles.text_black, marginTop: 10, marginBottom: 20}}>
            订单号：{data.xmbzNo}
          </Text>
          <Text style={{...commonStyles.text_black, marginTop: 10, marginBottom: 20}}>
            原配送地址：{data.address1}
          </Text>
          <View>
            <TouchableOpacity style={{...styles.btn, bottom: 10}} activeOpacity={1} onPress={() => {
              navigator.navigate("SearchAddressMap", {
                address: {
                  name: data.address1,
                  longitude: parseFloat(data.addressLng),
                  latitude: parseFloat(data.addressLat),
                }
              })
            }}>
                <Text>修改定位</Text>
            </TouchableOpacity>
            <View style={styles.textInput}>
                <TextField
                    multiline
                    hideUnderline
                    black333
                    maxLength={200}
                    value={address.name}
                    containerStyle={{flex: 1}}
                    onChangeText={name => {
                      const newAddress = {
                        ...address,
                        name: name,
                      }
                      this.setState({
                        address: newAddress,
                      })
                    }}
                    text14
                    placeholder="请输入新配送地址"/>
            </View>
          </View>
          <Text style={{...commonStyles.text_black, marginTop: 10, marginBottom: 10}}>
            原配送时间：{data?.delySTime} - {data?.delyETime}
          </Text>
          <Text style={{...commonStyles.text_black, marginTop: 10, marginBottom: 10}}>
            配送时间：{timer?.delySTime} - {timer?.delyETime}
          </Text>
          <View
            style={{
              backgroundColor: '#f7f7f7',
              borderRadius: 5,
              marginBottom: 5,
            }}>
            <FlatList
              data={dataList}
              style={{height: 150}}
              showsVerticalScrollIndicator={false}
              contentContainerStyle={{flexGrow: 1}}
              keyExtractor={(item, index) => 'dateType_' + index}
              renderItem={this.render_item}
              ItemSeparatorComponent={() => (
                <ListSeparator height={1} backgroundColor={'transparent'} />
              )}
            />
          </View>
          <View row centerV style={{marginTop: 10, marginBottom: 10}}>
            <Text>修改原因：</Text>
            <TouchableOpacity
              activeOpacity={1}
              style={styles.typeWrap}
              onPress={() =>
                this.pickerOrderTypeDialog && this.pickerOrderTypeDialog.show(reasonIndex, reasonList)
              }>
              <View marginR-3>
                <Text numberOfLines={1} style={commonStyles.text_black}>
                  {reason ? reason : '请选择原因'}
                </Text>
              </View>
              <Icon type="AntDesign" name="down" size={12} color={'#CCCCCC'} />
            </TouchableOpacity>
          </View>
          <View row style={{borderTopColor: '#eeeeee', borderTopWidth: 1}}>
            <Button
              flex
              label={'确定'}
              text14
              onPress={() => {
                const valid = this.validateParams();
                if (!valid) {
                  return;
                }
                this.confirmDialog.show("确定提交修改?");
              }}
            />
          </View>
        </View>

        <ConfirmDialog ref={r => this.confirmDialog = r} callBack={() => this.submit()} />
        <PickerTypeDialog
          ref={r => (this.pickerOrderTypeDialog = r)}
          onChecked={(reasonIndex, reasons) => {
            this.setState({reason: reasons[0], reasonIndex: reasonIndex});
          }}></PickerTypeDialog>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  roundedDialog: {
    backgroundColor: 'white',
    marginBottom: isIPhoneX ? 0 : 20,
    borderRadius: 4,
  },
  dropListView: {
    borderWidth: 1,
    borderColor: '#cccccc',
    borderRadius: 5,
    height: 35,
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 10,
  },
  itemWrap: {
    padding: 10,
  },
  itemWrap_checked: {
    padding: 10,
    backgroundColor: '#FFD8CE',
  },
  btn: {
    width: 80,
    height: 40,
    ...commonStyles.center,
    backgroundColor: '#F9D63B',
    borderRadius: 5,
  },
  textInput: {
    height: 100,
    backgroundColor: '#f7f7f7',
    padding: 10
  },
  typeWrap: {
    flexDirection: 'row',
    alignItems: 'center',
    width: 200,
    height: 40,
    justifyContent: 'space-between',
    borderRadius: 4,
    borderWidth: 1,
    borderColor: '#CCCCCC',
    paddingHorizontal: 10,
    backgroundColor: 'white',
    marginRight: 10,
  },
});
